package com.example.backstage.controller;

import com.example.backstage.config.security.LoginUserDetails;
import com.example.backstage.entity.Result;
import com.example.backstage.util.JwtUtil;
import com.example.backstage.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    RedisClient redisClient;

    @PostMapping("/login")
    public Result login(String username, String password) {

//         todo: 需要防止用户重复登录,重复产生token
//         todo: 防止用户在带有登录token的情况下继续登录获取token

        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            if (!Objects.isNull(authenticate)){

                LoginUserDetails principal = (LoginUserDetails) authenticate.getPrincipal();

                String jwtToken = JwtUtil.createJwt(principal,principal.getUser().getId(), principal.getUsername());
                Map<String, String> data = Map.of("token", jwtToken);
                String key = "login:token:"+jwtToken;

                //设置过期时间
                long expire = JwtUtil.expireTime().toInstant().toEpochMilli();
                long now = Instant.now().toEpochMilli();
                long time = expire - now;

                redisClient.set(key, jwtToken,time);

                return Result.ok(data);
            }
            return Result.ok("登录成功", null);

        } catch (AuthenticationException e) {
            log.info("{},账号:{},密码:{}", e.getMessage(), username, password);
            return Result.err("账号或密码错误");
        }
    }

    private boolean existsInsetToken(String key,String jwtToken){
        //设置过期时间
        long expire = JwtUtil.expireTime().toInstant().toEpochMilli();
        long now = Instant.now().toEpochMilli();
        long time = expire - now;

        redisClient.set(key, jwtToken,time);
        return false;
    }

    @GetMapping("/login")
    public Result getLogin() {
        return Result.err("请求错误");
    }
}
